import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:date_format/date_format.dart';
import 'package:helloworld/res/datetime.dart';
import 'package:helloworld/res/payData.dart';
import 'package:dio/dio.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'dart:ui';
class Pay extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Pay();
  }
}

class _Pay extends State<Pay> with WidgetsBindingObserver{
  int _index;
  int flag = 1;
  Color _color;
  Color _textColor;
  Color _payColor;
  Color _boxColor;
  Color _loadColor;
  Color _tapColor;
  _getData(String paymonth,String payyear) async{
    Response response = await Dio().post("http://123.207.114.127:1314/pay/selectByDate",queryParameters: {
      'paymonth':paymonth,
      'payyear':payyear
    });
    setState(() {
      if(response.data.length==0){
        flag = 0;
      }
      payData = response.data;
    });
  }
 Future<Null> _refresh()async{
    setState(() {
      flag =1;
      payData.clear();
    });
    await _getData('${formatDate(date, [mm, ])}','${formatDate(date, [yyyy, ])}');
    return;
  }
  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if(window.platformBrightness==Brightness.dark){
      _color = Colors.black12;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _payColor = Colors.white;
      _boxColor = Colors.grey;
      _tapColor = Colors.black45;
    }else{
      _color = Colors.white;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _payColor = Colors.black54;
      _boxColor = Colors.black26;
      _tapColor = Colors.black12;
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    if(window.platformBrightness==Brightness.dark){
      _color = Colors.black12;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _payColor = Colors.white;
      _boxColor = Colors.grey;
      _tapColor = Colors.black45;
    }else{
      _color = Colors.white;
      _loadColor = Colors.lightBlue;
      _textColor = Colors.black54;
      _payColor = Colors.black54;
      _boxColor = Colors.black26;
      _tapColor = Colors.black12;
    }
    _getData('${formatDate(date, [mm, ])}','${formatDate(date, [yyyy, ])}');
  }
  Widget loadingData(){
    if(payData.length==0&&flag==1){
      return Container(
          child: Center(
            child: Loading(indicator: BallPulseIndicator(), size: 100.0,color: _loadColor),
          ));
    }else if(payData.length==0&&flag==0){
      return Container(
          child: Center(
            child: ListView(
              children: <Widget>[
                SizedBox(height: 200,),
                Center(
                  child: Text('暂无支付信息',style: TextStyle(color: _textColor,fontSize: 30),),
                )
              ],
            ),
          ));
    } else{
      return ListView(
        physics:  AlwaysScrollableScrollPhysics(),
        children: payData.asMap().keys.map((f) {
          return Column(
            children: <Widget>[
              firstLine(f),
              Container(
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          // 设置单侧边框的样式
                            color: Colors.grey,
                            width: 0.2,
                            style: BorderStyle.solid))
                ),
                child: ListTile(
                  leading: Icon(Icons.monetization_on,size: 40,),
                  title: Text(payData[f]['payname']),
                  subtitle: Text(payData[f]['paydate']),
                  trailing: Text(
                    payData[f]['pay'].toStringAsFixed(2),
                    style: TextStyle(fontSize: 15),
                  ),
                  selected: f == _index,
                  onTap: () {
                    setState(() {
                      _index = f;
                      Navigator.pushNamed(context, '/payDetail',
                          arguments: {'id': _index});
                    });
                  },
                ),
              ),
              myDivider(f)
            ],
          );
        }).toList(),
      );
    }
  }
  Widget loadingTotal(){
    if(payData.length==0){
      return Text(
        '0.00',
        style: TextStyle(color: _payColor, fontSize: 30),
      );
    }else{
      return myPay(payData,_payColor);
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: Column(
//        mainAxisAlignment:  MainAxisAlignment.center,
        children: <Widget>[
          Container(
            padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
            decoration: BoxDecoration(
              color: _color,
            // gradient: LinearGradient(
            //   begin: Alignment.centerLeft,
            //   end: Alignment.centerRight,
            //   colors: [Colors.lightBlueAccent, Colors.deepPurpleAccent],
            // ),
            ),
            // height: 100,
            width: double.infinity,
            child: Row(
              children: <Widget>[
                //时间
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        child: InkWell(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text('${formatDate(date, [yyyy, '年'])}',style: TextStyle(fontSize: 15,color: _textColor),),
                              Row(
                                children: <Widget>[
                                  Text('${formatDate(date, [mm, '月'])}',style: TextStyle(fontSize: 25,color: _payColor),),
                                  Icon(Icons.arrow_drop_down)
                                ],
                              )

                            ],
                          ),
                          onTap: (){
                            DatePicker.showDatePicker(
                              context,
                              onMonthChangeStartWithFirstDate: true,
                              pickerTheme: DateTimePickerTheme(
                                showTitle: true,
                                confirm: Text('确定', style: TextStyle(color: Colors.black54,fontSize: 20)),
                                cancel: Text('取消', style: TextStyle(color: Colors.black54,fontSize: 20)),
                              ),
                              minDateTime: DateTime.parse('2020-01-01'),
                              maxDateTime: DateTime.parse('2099-12-31'),
                              initialDateTime: DateTime.now(),
                              dateFormat: 'yyyy-MMMM',
                              locale: DateTimePickerLocale.zh_cn,
                              onConfirm: (dateTime, List<int> index) {
                                setState(() {
                                  date = dateTime;
                                  _refresh();
                                });

                              },
                            );
                          },
                        ),
                      )
                    ],
                  ),
                  flex: 1,
                ),

                //竖线
                Expanded(
                  child: Container(
                    height: 40,
                    width: 1,
                    decoration: BoxDecoration(
                        border: Border.all(color: _boxColor)
                    ),
                  ),
                  flex: 0,
                ),
                //支出
                Expanded(
                  child: Container(
                    // padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              child: Text('支出',style: TextStyle(fontSize: 15,color: _textColor),),
                            ),
                            loadingTotal()
                          ],
                        )
                      ],
                    ),
                  ),
                  flex: 2,
                )

              ],
            ),
          ),
          Expanded(
            child: Container(
              child: RefreshIndicator(
                displacement: 20,
                child: loadingData(),
                onRefresh: _refresh,
              ),
              // padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
            ),
          ),
        ],
      ),
    );
  }
  Widget firstLine(int index){
    if(index==0){
      return Container(
        color: _tapColor,
        padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
        width: double.infinity,
        child: Row(
          children: <Widget>[
            SizedBox(width: 10,),
            Expanded(
              flex: 5,
              child: Text("${payData[0]['paydate']}"),
            ),
            Expanded(
              flex: 20,
              child: Container(
                alignment: Alignment.centerRight,
                child: Text("日支出: -22元"),
              ),
            ),
            SizedBox(width: 10,)
            // Padding(
            //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            //   child: Container(
            //     decoration: BoxDecoration(
            //       border: Border.all(width: 0.5,color: _boxColor),
            //     ),
            //   ),
            // ),
            // SizedBox(height: 20,)
          ],
        ),
      );
    }else{
      return SizedBox(height: 0,);
    }
  }
  Widget myDivider(int index){
    if(index<payData.length-1){
      if( payData[index]['payday']==payData[index+1]['payday']){
        return SizedBox(height: 0,);
      }else{
        return Column(
          children: <Widget>[
            // SizedBox(height: 20,),
            Container(
              color: _tapColor,
              padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
              width: double.infinity,
              child: Row(
                children: <Widget>[
                  SizedBox(width: 10,),
                  Expanded(
                    flex: 1,
                    child: Text("${payData[index+1]['paydate']}"),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Text("日支出: -22元"),
                    ),
                  ),
                  SizedBox(width: 10,),
                ],
              ),
            )
            // Padding(
            //   padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
            //   child: Container(
            //     decoration: BoxDecoration(
            //       border: Border.all(width: 0.5,color: _boxColor),
            //     ),
            //   ),
            // ),
            // SizedBox(height: 20,)
          ],
        );
      }
    }else{
      return SizedBox(height: 0,);
    }
    // return SizedBox(height: 10,);
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}

class myPay extends StatelessWidget {
  double _payCount = 0;
  Color _payColor;
  myPay(List payData,Color payColor) {
    _payColor = payColor;
    for (int i = 0; i < payData.length; i++) {
      _payCount = _payCount + payData[i]['pay'];
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text(
      _payCount.toStringAsFixed(2),
      style: TextStyle(color: _payColor, fontSize: 30),
    );
  }
}